package com.jming.jike.service.backend.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jming.jike.common.BusinessException;
import com.jming.jike.common.PageResult;
import com.jming.jike.dto.backend.EmployeeDTO;
import com.jming.jike.dto.backend.LoginDTO;
import com.jming.jike.dto.backend.UpdatePasswordDTO;
import com.jming.jike.entity.Employee;
import com.jming.jike.enums.StatusEnum;
import com.jming.jike.mapper.EmployeeMapper;
import com.jming.jike.service.backend.EmployeeService;
import com.jming.jike.util.CopyBeanUtils;
import com.jming.jike.vo.backend.EmployeeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import static com.jming.jike.enums.StatusEnum.STOP_STATUS;

/**
 * 员工信息(Employee)表服务实现类
 *
 * @author makejava
 * @since 2022-04-16 02:02:52
 */
@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    public Boolean insert(EmployeeDTO employeeDTO) {

        log.info("EmployeeServiceImpl insert 添加用户信息 入参{}", JSON.toJSONString(employeeDTO));
        // 根据用户名查询用户信息
        Employee employee = employeeMapper.selectOne(Wrappers.<Employee>lambdaQuery()
                .eq(Employee::getUserName, employeeDTO.getUserName())
                .last("limit 1"));

        if (!ObjectUtils.isEmpty(employee)) {
            throw new BusinessException("用户名已存在!");
        }

        employee = CopyBeanUtils.copyBean(employeeDTO, new Employee());
        // 设置默认密码 并做MD5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("jike666".getBytes()));

        // 添加用户信息
        return employeeMapper.insert(employee) > 0;
    }

    @Override
    public Boolean update(EmployeeDTO employeeDTO) {

        log.info("EmployeeServiceImpl insert 修改用户信息 入参{}", JSON.toJSONString(employeeDTO));
        // 查询用户信息
        Employee employee = employeeMapper.selectById(employeeDTO.getId());

        if (ObjectUtils.isEmpty(employee)) {

            throw new BusinessException("用户不存在!");
        }

        // 修改用户信息 并返回修改结果
        return employeeMapper.updateById(CopyBeanUtils.copyBean(employeeDTO, new Employee())) > 0;
    }

    @Override
    public Boolean updateStatus(Long id, Integer status) {

        // 检查状态
        StatusEnum.checkStatus(status);

        // 查询用户信息
        Employee employee = employeeMapper.selectById(id);
        if (ObjectUtils.isEmpty(employee)) {

            throw new BusinessException("用户不存在!");
        }

        // 修改员工状态
        return employeeMapper.updateById(Employee.builder().id(id).status(status).build()) > 0;
    }

    @Override
    public PageResult<EmployeeVO> pageQuery(EmployeeDTO employeeDTO) {

        log.info("EmployeeServiceImpl insert 分页查询员工列表 入参{}", JSON.toJSONString(employeeDTO));
        // 分页查询员工列表
        Page<Employee> employeePage = employeeMapper.selectPage(new Page<>(employeeDTO.getPageIndex(), employeeDTO.getPageSize()), Wrappers.<Employee>lambdaQuery()
                .like(StringUtils.hasText(employeeDTO.getUserName()), Employee::getUserName, employeeDTO.getUserName())
                .orderByDesc(Employee::getId));

        if (ObjectUtils.isEmpty(employeePage)
                || CollectionUtils.isEmpty(employeePage.getRecords())) {

            throw new BusinessException("员工列表空");
        }

        // 返回结果
        return new PageResult<>((int) employeePage.getCurrent(), (int) employeePage.getSize(),
                (int) employeePage.getTotal(), CopyBeanUtils.copyBeanList(employeePage.getRecords(), EmployeeVO.class));
    }

    @Override
    public Boolean updatePassword(UpdatePasswordDTO updatePasswordDTO) {

        // 检查密码
        if (!updatePasswordDTO.getPassword().equals(updatePasswordDTO.getSurePassword())) {
            throw new BusinessException("两次输入的密码不一致!");
        }

        // 查询员工信息
        Employee employee = employeeMapper.selectById(updatePasswordDTO.getId());

        if (ObjectUtils.isEmpty(employee)) {
            throw new BusinessException("员工不存在!");
        }

        // 检查原始密码
        if (!employee.getPassword().equals(DigestUtils.md5DigestAsHex(updatePasswordDTO.getOldPassword().getBytes()))) {
            throw new BusinessException("原密码不正确!");
        }

        // 修改密码并返回结果
        return employeeMapper.updateById(Employee.builder().id(updatePasswordDTO.getId())
                .password(updatePasswordDTO.getPassword()).build()) > 0;
    }

    @Override
    public Employee login(LoginDTO loginDTO) {

        // 查询用户信息
        Employee employee = employeeMapper.selectOne(Wrappers.<Employee>lambdaQuery()
                .eq(Employee::getUserName, loginDTO.getUserName()).last("limit 1"));

        if (ObjectUtils.isEmpty(employee)) {

            throw new BusinessException("用户不存在, 请检查用户名!");
        }

        if (STOP_STATUS.getCode().equals(employee.getStatus())) {

            throw new BusinessException("用户已被禁用, 请联系管理员!");
        }

        if (!employee.getPassword().equals(DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes()))) {

            throw new BusinessException("密码不正确!");
        }

        // 登录成功 返回用户信息
        employee.setPassword(null);
        return employee;
    }

}
